<?php

namespace app\common\model;
use think\Model;
use think\Db;

/**
 * 打印
 */
class Prt extends Model {
	protected $name = 'mall_orderprt';

	// 开启自动写入时间戳
	protected $autoWriteTimestamp = false;

	function order_printer($agent_id) {
		return db('agent_prt')->where("agent_id",$agent_id)->find();
	}
	function print_order6($order_id){
		$order = db("agent_syorder")->find($order_id);
		$total_price=$order['total_price'];
		$pay_price=$order['pay_price'];
		$dk=$order['need_score'];
		$zs=$order['give_score'];
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$content="<FH2><FB><FW2> {$agent['agent_name']}</FW2></FB></FH2>\r\n";
		$content.= "备注：{$order['message']}\r\n";
		$content.= "订单编号：{$order['sn']}\r\n";
		if($order['user_id']){
			$users = db('info_user')->field('id,mobile')->where('id',$order['user_id'])->find();
			$content.= $users['mobile']?"会员电话：{$users['mobile']} \r\n":"会员电话：\r\n";
			$content.= $users['id']?"会员id：{$users['id']} \r\n":"会员id：\r\n";  
		}
		
		$content.= $order['emp_id']?"收银员id：{$order['emp_id']} \r\n":'收银员id：0';
		
		$content.="\r\n合计：{$total_price}￥ \r\n实际支付：{$pay_price}￥\r\n使用鼓励金：{$dk}\r\n"."赠送鼓励金：{$zs}\r\n下单时间：" . $order['add_time'] . "\r\n打印时间：" . date('Y-m-d H:i:s', time());
		$url=config("API_DOMAIN")."api/sy/sk?oid=$order_id";
		$content .="\r\n<QR>$url</QR>";
		//print_r($content);die;
		$printer =$this->order_printer($order['agent_id']);
		//print_r($content);die;
		$machine_code = $printer['machine_code'];
		//打印机终端号
		$msign = $printer['msign'];
		
		$partner = '16764';
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);
	}
	//打印线下订单未支付
	function print_order2($order_id) {
		$order = db("agent_syorder")->find($order_id);
		$order['total_price']=number_format($order['total_price'],2);
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$orderitem="";
		$items=db("agent_syorder_items")->where('order_id',$order['id'])->select();
		if($items){
			foreach ($items as $value) {
				$name = mb_strimwidth($value['name'], 0, 15, '', 'UTF-8');
				$price = $value['price']*$value['num'] ;
				$orderitem .= "{$name} {$value['price']}/{$value['unit']} {$value['num']}{$value['unit']} {$price}\r";
			}
		}
		$content ="<FH2><FS><FW2>*{$agent['agent_name']}*</FS></FW2></FH2>\r\r";
		if($order['house_id']){
			$house=db("agent_house")->where("id",$order['house_id'])->field("name")->find();
			$content.="桌台号：{$house['name']}\r\n";
		}
		$head="商品名   单价   数量   合计 \r ";
		
		$content .= "订单编号：{$order['sn']}\r\n电话：{$agent['tel']}\r\n会员：\r\n--------------------------------\r\n";
		$content .="<FH>{$head}{$orderitem}</FH>\r\n合计：{$order['total_price']}￥\r\n会员价：{$order['total_price']}￥抵{$order['need_score']}\r\n零售价：{$order['total_price']}￥ 送{$order['give_score']}\r\n下单时间：{$order['add_time']}\r\n打印时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
		$url=config("API_DOMAIN")."api/sy/sk?oid=$order_id";
		$content .="\r\n<QR>$url</QR>";
		//print_r($content);die;
		$printer =$this->order_printer($order['agent_id']);
		//print_r($content);die;
		$machine_code = $printer['machine_code'];
		//打印机终端号
		$msign = $printer['msign'];
		
		$partner = '16764';
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);

	}
	//打印加单订单
	function print_items($order_id){
		$wh['order_id']=$order_id;
		$wh['dy_status']=0;	
		$items=db('agent_syorder_items')->where($wh)->select();
		$order=db('agent_syorder')->where("id",$order_id)->field("sn,agent_id,house_id,chain_id")->find();
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$orderitem="";
		$total_price=0;
		$total_price1=0;//加单总价
		$orderitem1="";
		$goodtps;
		foreach ($items as $value) {
			$goodtps[$value['type_id']][]=$value;
		}
		$tyname="";
		foreach ($goodtps as $v=>$k) {
			$gd_type=db('agent_type')->where("id",$v)->field("type_name")->find();
			$orderitem.="<tr><td>............".$gd_type['type_name']."..............</td></tr>";
			foreach($k as $i){
				$name = mb_strimwidth($i['name'], 0, 15, '', 'UTF-8');
				$price = $i['price'] ;
				$total_price+=$price;
				$orderitem .= "<tr><td>{$name}</td><td>{$i['num']}</td><td>{$price}</td></tr>";
			}
		}
		$content ="<FH2><FS><FW2>*{$agent['agent_name']}*</FS></FW2></FH2>\r\r";
		$house_prt="";
		if($order['house_id']){
			$house=db("agent_house")->where("id",$order['house_id'])->field("name,nums,memo")->find();
			$house_prt.="桌台号：{$house['name']}  人数{$house['nums']}\r\n";
			$house_prt.="备注：{$house['memo']}  \r\n";
		}
		$content .=$house_prt;
		$head="<tr><td>品名</td><td>数量</td><td>价格</td></tr>";
		$order_prt = "订单编号：{$order['sn']}\r\n电话：{$agent['tel']}\r\n";
		$content.=$order_prt;
		$content .="<table>{$head}{$orderitem}</table>\r\n合计：{$total_price}￥ \r\n下单时间：" . date('Y-m-d H:i:s', time()) . "\r\n打印时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
		$url=config("API_DOMAIN")."api/sy/sk?oid=$order_id";
		$content .="\r\n<QR>$url</QR>";
		$printer =$this->order_printer($order['agent_id']);
		$machine_code = $printer['machine_code'];
		$msign = $printer['msign'];		
		$partner = '16764';
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);
		if($printer['machine_code1']&&$printer['msign1']){
			foreach ($goodtps as $v=>$k) {
				$content1 ="<FH2><FS><FW2>*{$agent['agent_name']}*</FS></FW2></FH2>\r\r";
				$gd_type=db('agent_type')->where("id",$v)->field("type_name")->find();
				$content1 .="<FH2><FS><FW2>*{$gd_type['type_name']}*</FS></FW2></FH2>\r\r";
				$content1 .=$house_prt;
				$content1 .=$order_prt;
				foreach($k as $i){
					$name = mb_strimwidth($i['name'], 0, 15, '', 'UTF-8');
					$price = $i['price'] ;
					$total_price+=$price;
					$orderitem1 .= "<tr><td>{$name}</td><td>{$i['num']}</td><td>{$price}</td></tr>";
				}
				$content1 .="<table>{$head}{$orderitem1}</table>\r\n合计：{$total_price1}￥ \r\n下单时间：" . date('Y-m-d H:i:s', time()) . "\r\n打印时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
				$this-> action_print($partner, $printer['machine_code1'], $content1, $apiKey, $printer['msign1']);
			}	
		}	
		db('agent_syorder_items')->where($wh)->update(['dy_status'=>1]);
	}
	function print_items2($order_id){
		$wh['order_id']=$order_id;
		$items=db('agent_syorder_items')->where($wh)->select();
		$order=db('agent_syorder')->where("id",$order_id)->field("sn,agent_id,house_id,chain_id")->find();
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$orderitem="";
		$total_price=0;
		$goodtps;
		foreach ($items as $value) {
			$goodtps[$value['type_id']][]=$value;
		}
		$tyname="";
		foreach ($goodtps as $v=>$k) {
			$gd_type=db('agent_type')->where("id",$v)->field("type_name")->find();
			$orderitem.="<tr><td>............".$gd_type['type_name']."............</td></tr>";
			foreach($k as $i){
				$name = mb_strimwidth($i['name'], 0, 15, '', 'UTF-8');
				$price = $i['price'] ;
				$total_price+=$price;
				$orderitem .= "<tr><td>{$name}</td><td>{$i['num']}</td><td>{$price}</td></tr>";
			}
		}
		$content ="<FH2><FS><FW2>*{$agent['agent_name']}*</FS></FW2></FH2>\r\r";
		$house_prt="";
		if($order['house_id']){
			$house=db("agent_house")->where("id",$order['house_id'])->field("name,nums")->find();
			$house_prt.="桌台号：{$house['name']}  人数{$house['nums']}\r\n";
		}
		$content .=$house_prt;
		$head="<tr><td>品名</td><td>数量</td><td>价格</td></tr>";
		$order_prt = "订单编号：{$order['sn']}\r\n电话：{$agent['tel']}\r\n";
		$content.=$order_prt;
		$content .="<table>{$head}{$orderitem}</table>\r\n合计：{$total_price}￥ \r\n下单时间：" . date('Y-m-d H:i:s', time()) . "\r\n打印时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
		$url=config("API_DOMAIN")."api/sy/sk?oid=$order_id";
		$content .="\r\n<QR>$url</QR>";
		$printer =$this->order_printer($order['agent_id']);
		$machine_code = $printer['machine_code'];
		$msign = $printer['msign'];		
		$partner = '16764';
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);
	}
	
		//单产品打印 和扫码打印
	function print_order3($order_id) {
		$order = db("log_paylog")->find($order_id);
		$good=db("agent_goods")->find($order['goods_id']);
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$content="<FH2><FB><FW2> {$agent['agent_name']}</FW2></FB></FH2>\r";
		$content.="{$order['order_sn']}\r";
		$content.="{$order['pay_time']}\r";
		if($good){//单产品
				$content.="................................\r";
			$content.="<FH>";
			$content.="品名 单价 数量 小计\r";
			$content.="{$good['goods_name']} {$good['sale_price']} {$order['goods_num']} {$order['origin_price']}\r";
			$content.="</FH>";
			$content.="................................\r";
			$content.="<FH>";
			$content.="合计：{$order['origin_price']}\r";	
		}
		$content.="付款：{$order['balance']}\r";
		$content.="鼓励金：{$order['member_score']}\r\r";
		$content.="          谢谢惠顾!\r 欢迎下次光临\r</FH>";
		//print_r($content);die;
		$printer =$this->order_printer($order['agent_id']);
		//print_r($content);die;
		$machine_code = $printer['machine_code'];
		//打印机终端号
		$msign = $printer['msign'];
		$partner = '16764';
//		//用户ID
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		//API密钥
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);

	}
	
	
//	门店码打印小票(商家收银系统打印小票)
	public function print_store($order_id){
		$order=db('log_paylog')->where("id",$order_id)->find();
		$good=db("agent_goods")->find($order['goods_id']);
		$agent=db('info_agent')->field('agent_name,tel')->find($order['agent_id']);
		$content="<FH2><FB><FW2> {$agent['agent_name']}</FW2></FB></FH2>\r\n";
		if($good){//单产品
				$content.="................................\r";
			$content.="<FH>";
			$content.="品名 单价 数量 小计\r";
			$content.="{$good['goods_name']} {$good['sale_price']} {$order['goods_num']} {$order['origin_price']}\r";
			$content.="</FH>";
			$content.="................................\r";
			$content.="<FH>";
		}
		
		$total_price=$order['origin_price'];
		$pay_price=$total_price;
		$dk=0;
		$zs=0;
		if($order['member_score']>0){
			$pay_price=$total_price+$order['np_price'];
			$zs=$order['member_score'];
		}else{
			$dk=$order['member_score'];
		}	
		$users = db('info_user')->field('id,mobile')->where('id',$order['uid'])->find();
		$content.= "订单编号：{$order['order_sn']}\r\n";
		$content.= $users['mobile']?"会员电话：{$users['mobile']} \r\n":"会员电话：\r\n";
		$content.= $users['id']?"会员id：{$users['id']} \r\n":"会员id：\r\n";  
		$content.= $order['clerk_id']?"收银员id：{$order['clerk_id']} \r\n":'收银员id：0';
		
		$content.="\r\n合计：{$total_price}￥ \r\n实际支付：{$pay_price}￥\r\n使用鼓励金：{$dk}\r\n"."赠送鼓励金：{$zs}\r\n下单时间：" . $order['add_time'] . "\r\n打印时间：" . date('Y-m-d H:i:s', time());
		$url=config("API_DOMAIN")."api/sy/sk?oid=$order_id";
		$content .="\r\n<QR>$url</QR>";
		$printer =$this->order_printer($order['agent_id']);
		$machine_code = $printer['machine_code'];
		$msign = $printer['msign'];		
		$partner = '16764';
		$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
		$this-> action_print($partner, $machine_code, $content, $apiKey, $msign);
	}
/**
 * 生成签名sign
 * @param  array $params 参数
 * @param  string $apiKey API密钥
 * @param  string $msign 打印机密钥
 * @return   string sign
 */
public function generateSign($params, $apiKey,$msign)
{
    //所有请求参数按照字母先后顺序排
    ksort($params);
    //定义字符串开始所包括的字符串
    $stringToBeSigned = $apiKey;
    //把所有参数名和参数值串在一起
    foreach ($params as $k => $v)
    {
        $stringToBeSigned .= urldecode($k.$v);
    }
    unset($k, $v);
    //定义字符串结尾所包括的字符串
    $stringToBeSigned .= $msign;
    //使用MD5进行加密，再转化成大写
    return strtoupper(md5($stringToBeSigned));
}
/**
 * 生成字符串参数
 * @param array $param 参数
 * @return  string        参数字符串
 */
public function getStr($param)
{
	$str = '';
	foreach ($param as $key => $value) {
		$str=$str.$key.'='.$value.'&';
	}
	$str = rtrim($str,'&');
	return $str;
}
/**
 * 打印接口
 * @param  int $partner     用户ID
 * @param  string $machine_code 打印机终端号
 * @param  string $content      打印内容
 * @param  string $apiKey       API密钥
 * @param  string $msign       打印机密钥
 */
public function  action_print($partner,$machine_code,$content,$apiKey,$msign)
{
	$param = array(
		"partner"=>$partner,
		'machine_code'=>$machine_code,
		'time'=>time(),
		);
	//获取签名
	$param['sign'] = $this->generateSign($param,$apiKey,$msign);
	$param['content'] = $content;
	$str = $this->getStr($param);
	return $this->sendCmd('http://open.10ss.net:8888',$str);
}
/**
 *  添加打印机
 * @param  int $partner     用户ID1		
 * @param  string $machine_code 打印机终端号
 * @param  string $username     用户名
 * @param  string $printname    打印机名称
 * @param  string $mobilephone  打印机卡号
 * @param  string $apiKey       API密钥
 * @param  string $msign       打印机密钥
 */
public function action_addprint($partner,$machine_code,$username,$printname,$mobilephone,$apiKey,$msign)
{
	$partner = '16764';
	$apiKey = 'c3d0c8f3b9c251a6e9f60199d8669aa5577337df';
	$username='760154680@qq.com';
	$param = array(
		'partner'=>$partner,
		'machine_code'=>$machine_code,
		'username'=>$username,
		'printname'=>$printname,
		'mobilephone'=>$mobilephone,
		);
	$param['sign'] = $this->generateSign($param,$apiKey,$msign);
	$param['msign'] = $msign;
	$str = $this->getStr($param);
	return $this->sendCmd('http://open.10ss.net:8888/addprint.php',$str);
}
/**
 * 删除打印机
 * @param  int $partner      用户ID
 * @param  string $machine_code 打印机终端号
 * @param  string $apiKey       API密钥
 * @param  string $msign        打印机密钥
 */
public function action_removeprinter($partner,$machine_code,$apiKey,$msign)
{
	$param = array(
		'partner'=>$partner,
		'machine_code'=>$machine_code,
		);
	$param['sign'] = $this->generateSign($param,$apiKey,$msign);
	$str = $this->getStr($param);
	return $this->sendCmd('http://open.10ss.net:8888/removeprint.php',$str);
}
/**
 * 发起请求
 * @param  string $url  请求地址
 * @param  string $data 请求数据包
 * @return   string      请求返回数据
 */
public function sendCmd($url,$data)
{
    $curl = curl_init(); // 启动一个CURL会话      
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址                  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测    
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在      
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交     
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转      
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer      
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求      
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包      
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循     
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容      
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 
           
    $tmpInfo = curl_exec($curl); // 执行操作      
    if (curl_errno($curl)) {      
       echo 'Errno'.curl_error($curl);      
    }      
    curl_close($curl); // 关键CURL会话      
    return $tmpInfo; // 返回数据      
}
}
